package cn.gov.msa.collection;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import cn.gov.msa.util.PropertiesTools;
import cn.gov.msa.util.WebServiceTools;
import net.sf.json.JSONObject;


public class SmsService {
	private static Logger logger = Logger.getLogger(SmsService.class);
	/**
	 * 单条短信发送
	 * @param phone 手机号码
	 * @param message 短信内容
	 * @return {"result":"1:成功/0:失败","info":"1:短信发送成功/0:失败原因", "batchId":"成功才会有短信发送批次号返回"}
	 */
	public static String sendSingleMessage(String phone, String message) {
		String url = PropertiesTools.readProperties("sms.url");
		String methods = PropertiesTools.readProperties("sms.method");
		String account = PropertiesTools.readProperties("sms.account");
		String password = PropertiesTools.readProperties("sms.password");
		String appId = PropertiesTools.readProperties("sms.appid");
		String senderName = PropertiesTools.readProperties("sms.sendername");
		
		if(StringUtils.isBlank(phone)){
			return "{\"result\":\"0\",\"info\":\"目标号码为空\"}";
		}
		
		if(StringUtils.isBlank(message)){
			return "{\"result\":\"0\",\"info\":\"短信内容为空\"}";
		}
		
		// 消息必须加【中国海事局】签名后缀，才能发送成功
		if(!message.endsWith("【中国海事局】")){
			message = message.concat("【中国海事局】");
		}
		
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("AppId", appId);
		jsonObj.put("SenderName", senderName);
		
	    String[] parameter = new String[]{account, password, phone, message, jsonObj.toString()};
	    
	    String result = "{\"result\":\"1\",\"info\":\"短信发送成功\"}";
	    
		try {
			result = WebServiceTools.getDatasByUrl(url, methods, parameter);
			logger.info("短信回复" + result);
			long sms = -9L;
			try {
				sms = Long.parseLong(result);
			} catch (Exception e) {
				logger.error("非数字类型", e);
				return "{\"result\":\"0\",\"info\":\"短信发送接口异常："+e.getMessage()+"\"}";
			}
			
			String info = "";
			String status = "0"; // 结果标志。默认为失败。
			
			JSONObject smsResp = new JSONObject();
			if(sms > 0){
				info = "短信发送成功";
				status = "1";
				smsResp.put("batchId", sms);
			} else if(sms == -1){
				info = "余额不足";
			} else if(sms == -2){
				info = "帐号或密码错误";
			} else if(sms == -3){
				info = "连接服务商失败";
			} else if(sms == -4){
				info = "超时";
			} else if(sms == -6){
				info = "短信内容为空";
			} else if(sms == -7){
				info = "目标号码为空";
			} else {
				info = "其他原因发送失败";
			}
			
			smsResp.put("result", status);
			smsResp.put("info", info);
			result = smsResp.toString();
		} catch (Exception e) {
			result = "{\"result\":\"0\",\"info\":\"短信发送接口异常："+e.getMessage()+"\"}";
			logger.error("短信接口异常.", e);
		}
		return result;
	}
	
}
